package com.cavy.platform.server.repository.impl;

import com.cavy.platform.server.domain.Project;
import com.cavy.platform.server.mapper.ProjectMapper;
import com.cavy.platform.server.repository.ProjectRepository;
import com.cavy.platform.server.util.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 唐旭
 * @Date 2018/7/17
 */
@Repository
public class ProjectRepositoryImpl implements ProjectRepository {
    private static final String PROJECT_DIR_NAME = "project";
    @Value("${cavy.workspace.dir}")
    private String workspaceDir;

    @Override
    public int countByName(String workspace, String name) {
        File file = getProjectDir(workspace, name);
        if (file.exists()) {
            return 1;
        }
        return 0;
    }

    @Override
    public File getProjectDir(String workspace, String name) {
        return new File(getProjectParentFile(workspace), name);
    }

    private String getProjectParentFile(String workspace) {
        return workspaceDir + File.separator + workspace + File.separator + PROJECT_DIR_NAME;
    }

    @Override
    public void create(Project project) {
        File projectDir = getProjectDir(project.getWorkSpace().getName(), project.getName());
        boolean mkdirs = projectDir.mkdirs();
        if (!mkdirs) {
            throw new RuntimeException("创建文件夹:" + projectDir.getPath() + "失败");
        }
    }

    @Override
    public void delete(Project project) {
        File projectDir = getProjectDir(project.getWorkSpace().getName(), project.getName());
        FileUtils.delFolder(projectDir.getPath());
    }

    @Override
    public List<Project> list(String name, String workSpace) {
        File dir = new File(getProjectParentFile(workSpace));
        String[] list;
        if (StringUtils.isEmpty(name)) {
            list = dir.list();
        } else {
            list = dir.list(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.contains(name);
                }
            });
        }
        if (list == null) {
            return Collections.emptyList();
        }
        List<Project> result = new ArrayList<>(list.length);
        for (String item : list) {
            result.add(ProjectMapper.INSTANCE.convertTo(item, workSpace));
        }
        return result;
    }
}
